#! /usr/bin/env python3
# -*- encoding:utf-8 -*-

import logging
import aiomysql
logging.basicConfig(level=logging.INFO)


async def create_pool(loop, **kw):
    logging.info("create database connection pool")
    global __pool
    __pool = await aiomysql.create_pool(
        host=kw.get('host', '127.0.0.1'),
        port=kw.get('port', 3306),
        user=kw['user'],
        password=kw['password'],
        db=kw['db'],
        charset=kw.get('charset', 'utf8'),
        autocommit=kw.get('autocommit', True),
        maxsize=kw.get('maxsize', 10),
        minsize=kw.get('minsize', 1),
        loop=loop)


async def select(sql, args, size=None, page=None):
    logging.info("sql:%s" % sql)
    # logging.info("args:%s" %  ",".join(args))
    if page is not None:
        sql += " limit %s,%s" % ((page.curPage - 1) * page.pageSize,
                                 page.pageSize)
    global __pool
    with (await __pool) as conn:
        cursor = await conn.cursor(aiomysql.DictCursor)
        await cursor.execute(sql.replace('?', '%s'), args or ())
        if size:
            rs = await cursor.fetchmany(size)
        else:
            rs = await cursor.fetchall()
        await cursor.close()
        logging.info("rows return : %s" % len(rs))
        return rs


async def execute(sql, args):
    logging.info("sql:%s" % sql)
    # logging.info("args:%s" %  ",".join(args))
    global __pool
    with (await __pool) as conn:
        try:
            cursor = await conn.cursor()
            await cursor.execute(sql.replace('?', '%s'), args)
            affect = cursor.rowcount
            await cursor.close()
            logging.info("rows affted : %s" % affect)
        except Exception as e:
            logging.error(e)
            raise
        return affect
